import machine, neopixel
import network
import time
from machine import Timer
import ntptime

SSID = "ChinaNet-UHci"
PASSWORD = "akwcz32m"
SYNC_TIME_INTERVAL = 7 * 24 * 60 * 60

class Clock:
    
    def __init__(self, hour=12, minute=0, second=0):
        self.np = neopixel.NeoPixel(machine.Pin(4), 60)
        self.hour = hour
        self.minute = minute
        self.second = second
        
    def setTime(self, hour, minute, second):
        i = int(((hour % 12) * 60 + minute) / 12)
        self.np[i] = (0, 0, 0)
        self.np[self.minute] = (0, 0, 0)
        self.np[self.second] = (0, 0, 0)
        
        self.hour = hour
        self.minute = minute
        self.second = second
        
    def run(self):
        self.np[self.second] = (0, 0, 0)
        self.second += 1
        if self.second >= 60:
            self.second = 0
        self.np[self.second] = (0, 0, 10)
        self.np.write()
        
    def tick(self):
        self.np[self.second] = (0, 0, 0)
        self.second += 1
        if self.second >= 60:
            self.second = 0
            self.np[self.minute] = (0, 0, 0)
            i = int(((self.hour % 12) * 60 + self.minute) / 12)
            self.np[i] = (0, 0, 0)
            
            self.minute += 1
            if self.minute >= 60:
                self.minute = 0
                self.hour += 1
                if self.hour >= 24:
                    self.hour = 0
            
        i = int(((self.hour % 12) * 60 + self.minute) / 12)
        self.np[i] = (10, 0, 0)
        v = self.np[self.minute]
        self.np[self.minute] = (v[0], 10, v[2])
        
        v = self.np[self.second]
        self.np[self.second] = (v[0], v[1], 10)
        self.np.write()
        
def do_connect(essid, password, onBusy):
    sta_if = network.WLAN(network.STA_IF)
    if not sta_if.isconnected():
        print('connecting to network...')
        sta_if.active(True)
        sta_if.connect(essid, password)
        while not sta_if.isconnected():
            onBusy()
            time.sleep_ms(100)
    print('network config:', sta_if.ifconfig())
    return sta_if

def symc_time(self):
    pass
    

def main():
    import utime
    
    clock = Clock()
    sta_if = do_connect("ChinaNet-UHci", "akwcz32m", clock.run)
    
    ntptime.settime()
    utc = utime.localtime()
    hour, minute, second = utc[3], utc[4], utc[5]
    hour += 8
    hour %= 24
    clock.setTime(hour, minute, second)
    
    sta_if.disconnect()
    sta_if.active(False)
    
    tim = Timer(-1)
    tim.init(period=1000, mode=Timer.PERIODIC, callback=lambda t:clock.tick())
    try:
        while True:
            time.sleep(1)
    except:
        tim.deinit()
        print('Clock Exit!')

if __name__ == '__main__':
    main()
